import 'package:flutter/material.dart';
import '../models/movieitem_model.dart';
import 'package:flutter_doban/request/request_api.dart';

import 'child_components/movie_list_item.dart';

class TopPage extends StatefulWidget {
  TopPage({Key key}) : super(key: key);

  @override
  _TopPageState createState() => _TopPageState();
}

class _TopPageState extends State<TopPage> with AutomaticKeepAliveClientMixin {

  List<MovieItemModel> movieList = List<MovieItemModel>();

  //当前的页数
  int _pageNumber = 1;
  int _pageSize = 10;
  int _total = 0;

  // 是否加载完毕了
  bool _isover = false;
  // 是否正在加载数据
  bool _isloading = true;
  ScrollController _scrollCtrl;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {

    _scrollCtrl = ScrollController();
    _scrollCtrl.addListener(() {
      //已经拉到底部了
      if(_scrollCtrl.position.pixels == _scrollCtrl.position.maxScrollExtent){
        //正在加载 或者 数据还没加载完毕 直接返回
        if(_isover || _isloading){
          return;
        }
        //数据全加载完了
        if(_pageNumber*_pageSize >= _total){
          setState(() {
            _isover = true;
          });
          return;
        }
        //页码自动增
        setState(() {
          _pageNumber++;
        });
        //再次请求数据
        getHotMovieList();
      }
    });

    //页面加载的时候先请求一次数据
    getHotMovieList();

    super.initState();
  }

  @override
  void dispose(){
    _scrollCtrl.dispose();

    super.dispose();
  }

  // 获取电影列表数据的方法
  getHotMovieList() async{
    //正在加载
    setState(() {
      _isloading = true;
    });

    var result = await RequestApi.getMovieList("top250", _pageNumber, _pageSize);
    List list = result.data['subjects'];
    setState(() {
       _total = result.data["total"];
      movieList.addAll(list.map((e) => MovieItemModel.fromJson(e)).toList());
      _isloading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Top250"),
        centerTitle: true,
      ),
      body: getBodyWidget(),
    );
  }

  Widget getBodyWidget(){
    return ListView.builder(
      itemCount: movieList.length,
      itemBuilder: (BuildContext context, int index) {
        return MovieListItem(movieList[index]);
      }
    );
  }
}